package com.briup.estore.common.service.impl;

import com.briup.estore.common.bean.RecommendShop;
import com.briup.estore.common.bean.Shop;
import com.briup.estore.common.dao.IRecommendShopDao;
import com.briup.estore.common.dao.IShopDao;
import com.briup.estore.common.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author adam
 * @date 2022/10/13
 */
@Service
public class ShopServiceImpl implements IShopService {
    @Autowired
    private IShopDao shopDao;
    @Autowired
    private IRecommendShopDao recommendShopDao;

    @Override
    public long countShop() {
        long count = shopDao.count();
        return count;
    }

    @Override
    public Page<Shop> findShops(String shopName, int pageNum, int pageSize) throws Exception {
        PageRequest request = PageRequest.of(pageNum - 1, pageSize);
        System.out.println(shopName);
        Page<Shop> data = shopDao.findByNameContains(shopName, request);
        if (data.isEmpty()) {
            throw new Exception("暂无数据");
        }
        return data;
    }

    @Override
    public List<Shop> findAllShops() {
        return shopDao.findAll();
    }

    @Override
    public List<Shop> findDiscount() {
        List<Shop> discountList = shopDao.findByDiscountOrderBySalesVolumeDesc(true);
        return discountList;

    }

    @Override
    public List<Shop> recommendShop(Long id) {
        List<RecommendShop> recommendShops = recommendShopDao.findByUserId(id);
        if (recommendShops.isEmpty()) {
            List<Shop> shops = shopDao.findAll(Sort.by(Sort.Direction.DESC, "visitVolume")).subList(0, 10);
            return shops;
        } else {
            List<Shop> shops = recommendShops.stream().sorted((x, y) -> x.getRecommendValue() > y.getRecommendValue() ? 1 : -1).map(i -> i.getShops()).limit(8).collect(Collectors.toList());
            return shops;

        }
    }

    @Override
    public Shop findShopById(Long id) {
        return shopDao.findById(id).orElseGet(null);
    }

    @Override
    public List<Shop> findByCategory(Long categoryId) {
        List<Shop> shops = shopDao.findByCategoryId(categoryId);
        return shops;
    }

    @Override
    public List<Shop> searchShop(String shopName) {

        return shopDao.findByNameContaining(shopName.toUpperCase());
    }

    @Override
    public void save(Shop shop) {
        shopDao.save(shop);
    }

    @Override
    public void updateShopStatus(Long id) {
        Shop shop = shopDao.findById(id).orElseGet(null);
        shop.setStat(!shop.isStat());
        save(shop);
    }


}
